const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
}

/*
 * 格式化时间
 * time:传入的时间,
 * cFormat: 生成的格式{y}-{m}-{d} {h}:{i}:{s}
 */
function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 格式时间 传入秒
function formatSecond(time) {
  var secondTime = parseInt(time); // 秒
  var minuteTime = 0; // 分
  var hourTime = 0; // 小时
  if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
    //获取分钟，除以60取整数，得到整数分钟
    minuteTime = parseInt(secondTime / 60);
    //获取秒数，秒数取佘，得到整数秒数
    secondTime = parseInt(secondTime % 60);
    //如果分钟大于60，将分钟转换成小时
    if (minuteTime > 60) {
      //获取小时，获取分钟除以60，得到整数小时
      hourTime = parseInt(minuteTime / 60);
      //获取小时后取佘的分，获取分钟除以60取佘的分
      minuteTime = parseInt(minuteTime % 60);
    }
  }
  var result = "" + parseInt(secondTime) + "秒";

  if (minuteTime > 0) {
    result = "" + parseInt(minuteTime) + "分" + result;
  }
  if (hourTime > 0) {
    result = "" + parseInt(hourTime) + "小时" + result;
  }
  return result;
}

// 时间对比
function CompareDate(d1, d2) {
  console.log('====== CompareDate ======')
  console.log(new Date(d1.replace(/-/g, "\/")) + '>' + d2 + '=' + ((new Date(d1.replace(/-/g, "\/"))) > (d2)))
  console.log(new Date(d1.replace(/-/g, "\/")).getTime() + '>' + d2.getTime() + '=' + ((new Date(d1.replace(/-/g, "\/"))).getTime() > (d2)))
  return ((new Date(d1.replace(/-/g, "\/"))).getTime() > (d2.getTime()));
}

function checkString(str) {
  var r = /^[0-9]*[1-9][0-9]*$/;
  console.log(r.test(str));
  return r.test(str);
}

// 判断是否授权
function isAuthorize(that) {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  wx.getSetting({
    success: res => {
      console.log('=================================')
      console.log(res)
      if (res.authSetting['scope.userInfo']) {
        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        wx.getUserInfo({
          success: res => {
            console.log('======== isAuthorize ========');
            console.log(res.userInfo);
            console.log('=============================');

            that.globalData.wxUserInfo = res.userInfo;
            wx.setStorageSync("wxUserInfo", res.userInfo);

            let wxType = wx.getSystemInfoSync().environment ? 0 : 1;

            if (wxType) {
              wx.login({
                success: function(e) {
                  console.log(e)
                  var data = {
                    // 获取openid
                    point_url: that.server.agentApi.getMember, // 客户小程序
                    code: e.code,
                    wxType: wxType,
                  };
                  that.server.getConnect(data).then(function(res) {
                    console.log(res);
                    wx.setStorageSync("openid", res.data.openid);
                    wx.setStorageSync("userInfo", res.data);
                    that.globalData.openid = res.data.openid;
                    that.globalData.userInfo = res.data;
                  }, function(res) {
                    that.showConfirm('提示', res.data.msg, false);
                  })
                }
              })
            } else {
              wx.qy.login({
                success: function (e) {
                  console.log(e)
                  var data = {
                    // 获取openid
                    point_url: that.server.agentApi.getMember, // 客户小程序
                    code: e.code,
                    wxType: wxType
                  };
                  that.server.getConnect(data).then(function (res) {
                    console.log(res);
                    wx.setStorageSync("openid", res.data.openid);
                    wx.setStorageSync("userInfo", res.data);
                    that.globalData.openid = res.data.openid;
                    that.globalData.userInfo = res.data;
                  }, function (res) {
                    that.showConfirm('提示', res.data.msg, false);
                  })
                }
              })
            }

            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            if (that.userInfoReadyCallback) {
              that.userInfoReadyCallback(res)
            }
          }
        })
      }
      wx.hideLoading();
    }
  })
}

// 小程序是否有更新
function updateWxApp() {
  // 获取小程序更新机制兼容
  if (wx.canIUse('getUpdateManager')) {
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function(res) {
      console.log('======== updateWxApp ========');
      console.log('hasUpdate:' + res.hasUpdate);
      console.log('=============================');
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function() {
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.clearStorageSync();
                updateManager.applyUpdate();
              } else {
                getApp().showConfirm('提示', '新版本将会在下次重启微信时更新', false)
              }
            }
          })
        })
        updateManager.onUpdateFailed(function() {
          // 新的版本下载失败
          wx.showModal({
            title: '已经有新版本了哟~',
            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
          })
        })
      }
    })
  } else {
    // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
    })
  }
}

/**
 * 初始化小程序相关设置
 */
function initDebugSetting(app) {
  let params = {
    point_url: app.server.agentApi.getWxappDebugConfig,
  }
  app.server.getConnect(params).then(function(res) {
    console.log('========小程序调试配置========');
    console.log(res);
    // 设置小程序是否打开调试
    getApp().globalData.enableDebug = res['data']['list']['enableDebug'];
    if (wx.getStorageSync('enableDebug') !== res['data']['list']['enableDebug']) {
      wx.setStorageSync('version', res['data']['list']['version']);
      wx.setEnableDebug({
        enableDebug: res['data']['list']['enableDebug']
      })
    }
    // 设置版本号,当版本号不是最新时,清除缓存
    getApp().globalData.version = res['data']['list']['version'];
    if (wx.getStorageSync('version') !== res['data']['list']['version']) {
      wx.clearStorageSync();
      wx.setStorageSync('version', res['data']['list']['version']);
      wx.navigateTo({
        url: '/pages/agent/authorization/authorization',
      })
    }
  })
}

// 获取首页配置
function loadHomepageConfig(app) {
  var that = this;
  var data = {
    point_url: app.server.agentApi.getWxappHomepage
  };
  app.server.getConnect(data).then(function (res) {
    let pluginList = [];
    for (let i in res.data) {
      if (res.data[i]['id'] === 3) {
        pluginList = res.data[i]['plugUnitList'];
        break;
      }
    }
    wx.setStorageSync('pluginList', pluginList);
    app.globalData.pluginList = pluginList;
  })
}

// 初始化客户端小程序样式
function initAgentWxappStyle(app, that, cb) {
  setTimeout(function() {
    let params = {
      point_url: app.server.agentApi.getWxappStyle,
    }
    app.server.getConnect(params).then(function(res) {
      loadHomepageConfig(app);
      console.log('========小程序样式配置========');
      console.log(res);
      // 设置风格
      let wxappTitle = res.data['wxappletName'] || '';
      let wxappLogo = res.data['member_wechat_icon_url'] || '';
      let mainColor = res.data['wxappletColor'] || '#fff';
      app.globalData['wxappStyle'] = {
        wxappletName: wxappTitle,
        wxappletLogo: wxappLogo,
        wxappletColor: mainColor,
        menuType: res.data['memberFormat'] || 1
      };
      wx.setStorageSync('wxappStyle', {
        wxappletName: wxappTitle,
        wxappletLogo: wxappLogo,
        wxappletColor: mainColor,
        menuType: res.data['memberFormat'] || 1
      });

      // 设置小程序服务环境
      app.globalData.config['ENV'] = res.data.env || 'CLOUD';
      // 设置底部导航栏
      app.globalData.config['selectedTarbarType'] = 'Agent';
      app.globalData.config['AgentTarbarList'] = res.data.tabbarList;
      res.data.adminHomePageUrl && (app.globalData.config['SwitchTabToAdminPageUrl'] = res.data.adminHomePageUrl);
      res.data.tabbarList && res.data.tabbarList.length>0 && (app.globalData.config['SwitchTabToAgentPageUrl'] = res.data.tabbarList[0].pagePath);

      // 设置用户中心相册是否显示,及显示背景
      app.globalData.config['agentPlugins']['album'] = (res.data.configs && res.data.configs['album']);
      // 设置工单背景是否显示,及显示背景
      app.globalData.config['agentPlugins']['workOrder'] = (res.data.configs && res.data.configs['workOrder']);

      // 设置顶部导航栏标题
      wx.setNavigationBarTitle({
        title: wxappTitle,
      })
      // 设置顶部导航栏样式
      wx.setNavigationBarColor({
        frontColor: '#ffffff', // 字体颜色
        backgroundColor: mainColor, // 背景色
      });
      // 设置上拉下拉背景色
      wx.setBackgroundColor({
        backgroundColorTop: mainColor, // 顶部窗口的背景色为白色
        backgroundColorBottom: '#ffffff', // 底部窗口的背景色为白色
      })

      // 设置tarbar
      app.utils.changeTarbarIcon(app, that, 'agent', cb);
    })
  }, 100)
}

// 初始化员工端小程序样式
function initAdminWxappStyle(app, that, cb) {
  setTimeout(function() {
    let params = {
      point_url: app.server.adminApi.getWxappStyle,
    }
    app.server.getConnect(params).then(function(res) {
      console.log('========小程序样式配置========');
      console.log(res);
      // 设置风格
      let wxappTitle = res.data['wxappletName'] || '';
      let wxappLogo = res.data['member_wechat_icon_url'] || '';
      let mainColor = res.data['wxappletColor'] || '#fff';
      app.globalData['wxappStyle'] = {
        wxappletName: wxappTitle,
        wxappletColor: mainColor,
        wxappletLogo: wxappLogo,
        menuType: res.data['memberFormat'] || 1
      };
      wx.setStorageSync('wxappStyle', {
        wxappletName: wxappTitle,
        wxappletColor: mainColor,
        wxappletLogo: wxappLogo,
        menuType: res.data['memberFormat'] || 1
      });

      // 设置底部导航栏
      app.globalData.config['selectedTarbarType'] = 'Admin';
      app.globalData.config['AdminTarbarList'] = res.data.tabbarList;

      // 设置顶部导航栏标题
      wx.setNavigationBarTitle({
        title: wxappTitle,
      })
      // 设置顶部导航栏样式
      wx.setNavigationBarColor({
        frontColor: '#ffffff', // 字体颜色
        backgroundColor: mainColor, // 背景色
      });
      // 设置上拉下拉背景色
      wx.setBackgroundColor({
        backgroundColorTop: mainColor, // 顶部窗口的背景色为白色
        backgroundColorBottom: '#ffffff', // 底部窗口的背景色为白色
      });

      // 设置tarbar
      app.utils.changeTarbarIcon(app, that, "admin", cb);
    })
  }, 100)
}

// 选择的图片转base64
function fileToBase64(file) {
  // console.log(file);
  let fileBase64 = wx.getFileSystemManager().readFileSync(file, 'base64');
  // console.log(fileBase64);
  return 'data:image/png;base64,' + fileBase64;
}

// tarbar图片修改
function changeTarbarIcon(app, that, type, cb) {
  const base64 = require('./base64.js');

  let mainColor = (app.globalData.wxappStyle && app.globalData.wxappStyle.wxappletColor) || '#18bc9c';
  

  let adminTarbarList = app.globalData.config['AdminTarbarList'] || [];
  let agentTarbarList = app.globalData.config['AgentTarbarList'] || [];

  // for (var i = 0; i < adminTarbarList.length; i++) {
  //   let temp = wx.getFileSystemManager().readFileSync(adminTarbarList[i].selectedIconSvg, 'binary');
  //   temp = temp.replace(/fill="#[a-zA-Z0-9]{0,6}"/g, 'fill="' + mainColor + '"');
  //   adminTarbarList[i].selectedIconPath = 'data:image/svg+xml;base64,' + base64.baseEncode(temp);
  // }

  // for (var i = 0; i < agentTarbarList.length; i++) {
  //   let temp = wx.getFileSystemManager().readFileSync(agentTarbarList[i].selectedIconSvg, 'binary');
  //   temp = temp.replace(/fill="#[a-zA-Z0-9]{0,6}"/g, 'fill="' + mainColor + '"');
  //   agentTarbarList[i].selectedIconPath = 'data:image/svg+xml;base64,' + base64.baseEncode(temp);
  // }

  if (that && typeof that.getTabBar === 'function' &&
    that.getTabBar()) {
    that.getTabBar().setData({
      selectedColor: mainColor,
      list: type === 'agent' ? agentTarbarList : adminTarbarList
    })
  }
  app.globalData.config.AdminTarbarList = adminTarbarList;
  app.globalData.config.AgentTarbarList = agentTarbarList;
  app.globalData.config.selectedColor = mainColor;

  app.initPage(app, that);

  cb && cb();
}

// 判断是否是设置的tabbar
function contrastTabbarList(path, tabbarList = []) {
  for (let i = 0; i < tabbarList.length; i++) {
    if (tabbarList[i]['pagePath'].indexOf(path) >= 0) {
      return true;
    }
  }
  return false;
}

// 判断参数在数组中的下标
function getArrayIndex(path, tabbarList=[]){
  for (let i = 0; i < tabbarList.length; i++) {
    if (tabbarList[i]['pagePath'].indexOf(path) >= 0) {
      return i;
    }
  }
  return null;
}

// 获取当前页面路径及参数
function getCurrentPageUrlWithArgs() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const url = currentPage.route
  const options = currentPage.options
  let urlWithArgs = `/${url}?`
  for (let key in options) {
    const value = options[key]
    urlWithArgs += `${key}=${value}&`
  }
  urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
  return urlWithArgs
}

module.exports = {
  formatTime: formatTime,
  checkString: checkString,
  formatSecond: formatSecond,
  compareDate: CompareDate,
  parseTime: parseTime,
  isAuthorize: isAuthorize,
  updateWxApp: updateWxApp,
  initAgentWxappStyle: initAgentWxappStyle,
  initAdminWxappStyle: initAdminWxappStyle,
  initDebugSetting: initDebugSetting,
  fileToBase64: fileToBase64,
  changeTarbarIcon: changeTarbarIcon,
  contrastTabbarList: contrastTabbarList,
  getArrayIndex: getArrayIndex,
  getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs
}